package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.CartAdapter;
import com.da.lon.wang.xlg.adapter.NoneCartAdapter;
import com.da.lon.wang.xlg.bean.CartBean;
import com.da.lon.wang.xlg.bean.CartBean.MResult.CartResult;
import com.da.lon.wang.xlg.bean.CartListBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.fragment.CartLienser;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.swipelistview.SwipeListView;
import com.da.lon.wang.xlg.util.BuyUtil;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.ScrollGridView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.osell.selection.util.DeviceUuidFactory;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class CartActivity extends BaseActivity implements CartLienser,
        OnClickListener {

    private static final int DELAY = 0;
    public static int deviceWidth;
    List<CartResult> datas;
    private Context context;
    private float sum = 0.0f;
    private TextView sumTv;
    private SwipeListView cartListView;
    private CartAdapter adapter;
    // 显示图片的消息队列，控制ListView控件刷新图片
    Handler showImageHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

        ;
    };
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case DELAY:
                    adapter.selectAll(true);
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private CheckBox all;
    private boolean isCan = true;
    private ScrollGridView noneGv;
    private List<String> nImgList;
    private List<String> nNameList;
    private List<String> nPricespeList;
    private List<String> nPriceList;
    private List<String> nZkList;
    private List<String> nUrList;
    private LinearLayout somethingLayout;
    private ScrollView nothingLayout;
    private LinearLayout topbagLayout;
    private LinearLayout bottom;
    private String needCoordinates;
    private ArrayList<Position> positions = new ArrayList<CartActivity.Position>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        setContentView(R.layout.ocoffee_cart_activity);

        somethingLayout = (LinearLayout) findViewById(R.id.ocoffee_cart_something);
        nothingLayout = (ScrollView) findViewById(R.id.ocoffee_cart_nothing);
        topbagLayout = (LinearLayout) findViewById(R.id.ocoffee_cart_topbag);
        topbagLayout.setVisibility(View.GONE);

        ImageButton topButton = (ImageButton) findViewById(R.id.ocoffee_top_left);
        topButton.setOnClickListener(this);
        initView();
        initView1();
    }

    @Override
    protected void onResume() {
        super.onResume();
        nNameList.clear();
        getData();
        sum = 0;
        sumTv.setText("合计: ￥0.00" + "\n不含运费");
        selectAll(false);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initView1() {
        TextView noneTv = (TextView) findViewById(R.id.ocoffee_cart_none_tv);
        noneGv = (ScrollGridView) findViewById(R.id.ocoffee_cart_none_gv);
        noneTv.setOnClickListener(this);
        nImgList = new ArrayList<>();
        nNameList = new ArrayList<>();
        nPricespeList = new ArrayList<>();
        nPriceList = new ArrayList<>();
        nZkList = new ArrayList<>();
        nUrList = new ArrayList<>();

    }

    private void initData() {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%" + "disp"));
        params.add("version", "21");
        params.put("deviceId", new DeviceUuidFactory(this).getDeviceUuid().toString());
        params.put("shop_id", MyApplication.getShopId());
        client.post(XLGConstants.URL + "Cart-disp", params,
                new JsonHttpResponseHandler("utf-8") {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        // TODO Auto-generated method stub
                        super.onSuccess(statusCode, headers, response);

                        try {
                            if ("000000".equals(response.getString("code"))) {
                                JSONObject result = response
                                        .getJSONObject("result");
                                CartListBean result2 = new CartListBean();
                                JSONArray array = result
                                        .getJSONArray("like_list");
                                JSONObject object = result
                                        .getJSONObject("area");

                                result2.setLike_list(array);
                                result2.setArea(object);

                                for (int i = 0; i < +result2.getLike_list()
                                        .length(); i++) {
                                    JSONObject obj = result2.getLike_list()
                                            .getJSONObject(i);
                                    nImgList.add(obj.getString("bigimage"));
                                    nNameList.add(obj.getString("name"));
                                    nPriceList.add(obj.getString("price"));
                                    nPricespeList.add(obj.getString("pricespe"));
                                    nZkList.add(obj.getString("zk"));
                                    nUrList.add(obj.getString("product_number"));

                                }
                                noneGv.setAdapter(new NoneCartAdapter(context,
                                        nImgList, nNameList, nPriceList,
                                        nPricespeList, nZkList));
                                noneGv.setOnItemClickListener(new OnItemClickListener() {

                                    @Override
                                    public void onItemClick(
                                            AdapterView<?> parent, View view,
                                            int position, long id) {
                                        // TODO Auto-generated method stub
                                        Intent intentr = new Intent(context,
                                                ProductsActivity.class);

                                        String product_number = nUrList
                                                .get(position);
                                        PreferenceUtils
                                                .getInstance()
                                                .SetSettingString(
                                                        PreferencesConfig.PRODUCT_NUMBER,
                                                        product_number);
                                        CartActivity.this
                                                .startActivity(intentr);

                                    }
                                });
                            }
                        } catch (JSONException e) {
                            // TODO: handle exception

                        }
                    }
                });

    }

    private void initView() {
        bottom = (LinearLayout) findViewById(R.id.bottom);
        all = (CheckBox) findViewById(R.id.all);
        sumTv = (TextView) findViewById(R.id.sum);
        Button finalbutton = (Button) findViewById(R.id.finalbutton);
        // 构造数据

        finalbutton.setOnClickListener(this);

        cartListView = (SwipeListView) findViewById(R.id.cart_listview);
        deviceWidth = getDeviceWidth();

        reload();

        all.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if (isCan && adapter != null) {
                    adapter.selectAll(arg1);
                }
            }
        });

    }

    private void reload() {

        cartListView.setSwipeMode(SwipeListView.SWIPE_MODE_LEFT);
        cartListView.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_REVEAL);
        // mSwipeListView.setSwipeActionRight(settings.getSwipeActionRight());
        cartListView.setOffsetLeft(deviceWidth * 3 / 4);
        // mSwipeListView.setOffsetRight(convertDpToPixel(settings.getSwipeOffsetRight()));
        cartListView.setAnimationTime(0);
        cartListView.setSwipeOpenOnLongPress(false);
    }

    private int getDeviceWidth() {

        return getResources().getDisplayMetrics().widthPixels;
    }

    private void getData() {
        try {
            HttpLoader<CartBean> loader = new HttpLoader<>(this, XLGConstants.URL
                    + "/Cart-disp", CartBean.class, 10 * 1000);
            AjaxParams params = new AjaxParams();

            params.put("id", MyApplication.getInstance().getSharedPreferences("user_info", MODE_PRIVATE).getString("user_id", ""));
            params.put("deviceId", new DeviceUuidFactory(this).getDeviceUuid().toString());

            params.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                    + "disp"));

            loader.setManagerListener(new OnWebLoadListener<CartBean>() {

                @Override
                public void OnStart() {
                    showDialog();
                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                }

                @Override
                public void onSuccess(CartBean t) {
                    dismissDialog();

                    CartBean bean = t;

                    if (t != null && "000000".equals(bean.getCode())) {

                        datas = bean.getResult().cart_result;
                        needCoordinates = bean.getResult().getNeedCoordinates();
                        if (datas != null && !datas.isEmpty()) {
                            bottom.setVisibility(View.VISIBLE);
                            somethingLayout.setVisibility(View.VISIBLE);
                            nothingLayout.setVisibility(View.GONE);
                            adapter = new CartAdapter(context, datas,
                                    CartActivity.this);
                            handler.sendEmptyMessageDelayed(DELAY, 100);
                            if (adapter != null) {
                                cartListView.setAdapter(adapter);
                            }
                            if (datas.size() > 1) {
                                topbagLayout.setVisibility(View.VISIBLE);
                            } else {
                                topbagLayout.setVisibility(View.GONE);
                            }
                        } else {
                            bottom.setVisibility(View.GONE);
                            somethingLayout.setVisibility(View.GONE);
                            nothingLayout.setVisibility(View.VISIBLE);
                            topbagLayout.setVisibility(View.GONE);
                            initData();
                        }
                    }
                }
            });
            loader.loadData(params);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    public void selectAll(boolean flag) {

        isCan = false;
        all.setChecked(flag);
        isCan = true;


    }

    @Override
    public void soleChage(float num) {
        sum = sum + num;
        if (sum >= 0) {
            DecimalFormat fnum = new DecimalFormat("##0.00");
            String dd = fnum.format(sum);
            sumTv.setText("合计: ￥" + dd + "\n不含运费");
        }
    }

    @Override
    public void can() {
        // TODO Auto-generated method stub
    }

    @Override
    public void delete(String id) {
        try {
            showDialog();
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.add("id", MyApplication.getUserId());
            params.add("ids", id);
            params.add("deviceId", new DeviceUuidFactory(this).getDeviceUuid().toString());
            params.add("shop_id", MyApplication.getShopId());
            params.add("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                    + "delete"));
            client.post(XLGConstants.URL + "Cart-delete", params,
                    new JsonHttpResponseHandler("utf-8") {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers,
                                              JSONObject response) {
                            dismissDialog();
                            try {
                                String code = response.getString("code");
                                if ("000000".equals(code)) {
                                    // sumTv.setText("合计: ￥0.00" + "\n不含运费");
                                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                                    sum = 0.0f;
                                    // all.setChecked(false);
                                    getData();
                                } else {
                                    ToastUtils.showShort(context,
                                            response.getString("message"));
                                }
                            } catch (JSONException e) {

                            }
                            super.onSuccess(statusCode, headers, response);
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers,
                                              String responseString, Throwable throwable) {
                            dismissDialog();
                            super.onFailure(statusCode, headers,
                                    responseString, throwable);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ocoffee_cart_none_tv:
                Intent intent = new Intent(context, ResultSearchActivity.class);
                startActivity(intent);
                break;

            case R.id.ocoffee_top_left:
                finish();
                break;

            case R.id.finalbutton:
                if (TextUtils.isEmpty(PreferenceUtils.getInstance()
                        .getSettingStr(PreferencesConfig.USER_KEY, ""))) {// 未登录
                    intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("isGotoHome", false);
                    context.startActivity(intent);
                } else if (adapter != null) {
                    String result = adapter.getIds();
                    if (result.equals("")) {
                        Toast.makeText(context, "你还没有选择商品", Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        new BuyUtil(this).getTakeGoodsType(result,
                                needCoordinates);
                    }
                }


                break;
        }
    }

    /**
     * 记录图片在集合中的位置和显示中的位置的对应关系
     *
     * @author Administrator
     */
    public class Position {
        public int index;
        public int i;
        public int j;

        public Position(int index, int i, int j) {
            this.index = index;
            this.i = i;
            this.j = j;
        }

    }
}
